package org.wiztools.te;

import org.wiztools.te.TEProcess;
import org.wiztools.te.TEMod;

import bsh.Interpreter;
import bsh.EvalError;

import java.io.FileNotFoundException;
import java.io.IOException;

import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;

public final class BSHBuilder{
	private static BSHBuilder bshb;
	
	private Interpreter intptr;
	
	// Singleton
	private BSHBuilder(){
		// do nothing!
	}
	
	public static BSHBuilder getInstance(){
		if(bshb==null){
			synchronized(BSHBuilder.class){
				if(bshb==null){
					bshb = new BSHBuilder();
					bshb.init();
				}
			}
		}
		return bshb;
	}
	
	public TEProcess getTep(String scriptName) throws EvalError, FileNotFoundException, IOException{
		intptr.set("__tep__", null);
		intptr.source(DirectoryConstants.BSH_PLUGIN+scriptName);
		return (TEProcess)intptr.get("__tep__");
	}
	
	private void init(){
		try{
			URLClassLoader cl = (URLClassLoader)TEPluginLoader.getInstance().getLibraryClassLoader();
			URL[] urls = cl.getURLs();
			
			intptr = new Interpreter();
			intptr.eval("java.net.URL[] urls = null");
			intptr.set("urls", urls);
			intptr.eval("for(java.net.URL url: urls){addClassPath(url);}");
			
			intptr.eval("import com.indiwiz.te.TEProcess");
			intptr.eval("import com.indiwiz.te.TEMod");
			intptr.eval("TEProcess __tep__");
			intptr.eval("setTEProcess(TEProcess tep){ __tep__ = tep;}");
		}
		catch(EvalError ee){
			// should not come here!
			ee.printStackTrace();
		}
		catch(MalformedURLException mue){
			mue.printStackTrace();
		}
	}
}
